'use strict';

const Controller = require('egg').Controller;
const jwt = require('jsonwebtoken');

class HomeController extends Controller {
  async login() {
    const { ctx, app } = this;
    const { username, password } = ctx.request.body
    const data = await app.mysql.get('login', { username, password })

    if (data) {
      const token = jwt.sign(data.username, "1901B")
      ctx.body = {
        code: 1,
        msg: "成功",
        token,
        data
      }
    } else {
      ctx.body = {
        code: 500,
        msg: '失败',
      }
    }
  }

  async resolve() {
    const { ctx, app } = this;
    const { username, password } = ctx.request.body
    const data = await app.mysql.get('login', { username })

    if (data) {
      ctx.body = {
        code: 500,
        msg: "账号已被注册"
      }
    } else {
      await app.mysql.insert('login', { username, password })
      ctx.body = {
        code: 1,
        msg: "注册成功",
        data
      }
    }
  }
}

module.exports = HomeController;